package com.rabbit.redis.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

/**
 * <h1>Redis Config类</h1>
 *
 * @author zjw
 * @date 2021/06/23
 */
@Configuration
@EnableConfigurationProperties(com.rabbit.redis.config.RedisProperties.class)
public class RedisConfig {

    public JedisPoolConfig jedisPoolConfig(RedisProperties redisProperties) {
        JedisPoolConfig pool = new JedisPoolConfig();
        pool.setMaxIdle(redisProperties.getPoolMaxIdle());
        pool.setMaxTotal(redisProperties.getPoolMaxTotal());
        pool.setMinIdle(redisProperties.getPoolMinIdle());
        return pool;
    }

    public RedisStandaloneConfiguration redisStandaloneConfiguration(RedisProperties redisProperties) {
        RedisStandaloneConfiguration redisStandaloneConfiguration =
                new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(redisProperties.getHost());
        redisStandaloneConfiguration.setDatabase(redisProperties.getDatabase());
        redisStandaloneConfiguration.setPort(redisProperties.getPort());
        if (StringUtils.hasText(redisProperties.getPassword())) {
            redisStandaloneConfiguration.setPassword(redisProperties.getPassword());
        }
        return redisStandaloneConfiguration;
    }

    public JedisConnectionFactory jedisConnectionFactory(RedisProperties redisProperties) {
        JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder()
                .usePooling()
                .poolConfig(jedisPoolConfig(redisProperties)).build();
        JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration(redisProperties), jedisClientConfiguration);
        factory.afterPropertiesSet();
        return factory;
    }

    @Bean(name = "StringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(RedisProperties redisProperties) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory(redisProperties));
        return template;
    }
}
